package system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/finishCheck")
public class finishCheck extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	int type=Integer.parseInt(req.getParameter("type"));
    	
    	int partNo=Integer.parseInt(req.getParameter("partNo"));
		int questionNo=Integer.parseInt(req.getParameter("questionNo"));
		
		String result="";
		
		HttpSession session=req.getSession();
        String testid=(String)session.getAttribute("testid");
		
		sqlOperation sql = new sqlOperation();
		
		if(type==1) {
			String questionId=(sql.getQuerySet("select question_id from questions where test_id='"+testid+"' and part_no='"+partNo+"' and question_no='"+questionNo+"'",1))[0];
			if(questionId.equals("")) {
				result = "{\"code\":\""+0+"\"}";
			}else result = "{\"code\":\""+1+"\"}";
		}else if(type==2) {
			int studentCount = sql.getCount("select COUNT(*) from user_inf where user_type='0'");
			String[] studentsId = sql.getQuerySet("select user_id from user_inf where user_type='0'",studentCount);
			for(int i=0;i<studentCount;i++) {
				int createStudent_Test=sql.getInsert("insert into student_test values('"+studentsId[i]+"','"+testid+"','0','0')");
			}
			int finish=sql.getUpdate("update testing set isFinished='1' where test_id='"+testid+"'");
			if(finish==1) {
				result = "{\"code\":\""+1+"\"}";
			}else result = "{\"code\":\""+0+"\"}";
			
		}
		
		resp.setContentType("application/json;charset=UTF-8");
		PrintWriter out = resp.getWriter();		
		out.write(result);
		
    }
  
}
